<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手交易平台 - 登录</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 400px;
        }
        .login-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"] {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
        }
        .login-btn {
            width: 100%;
            padding: 12px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        .login-btn:hover {
            background: #5a6fd8;
        }
        .register-link {
            text-align: center;
            margin-top: 20px;
        }
            .test-page-button-fixed {
            position: fixed !important;
            top: 0px !important;
            left: 0px !important; /* Changed to left for easier spotting */
            width: 120px !important;
            height: 60px !important;
            background-color: red !important;
            color: white !important;
            z-index: 99999 !important; /* Increased z-index */
            border: 5px solid yellow !important;
            font-size: 18px !important;
            text-align: center !important;
            line-height: 60px !important;
            text-decoration: none !important;
            font-weight: bold !important;
        }
    </style>
</head>
<body>
<a href="test-page.html" class="test-page-button-fixed">TEST</a>
<script>
    const currentPort = window.location.port;

    async function redirectToLoadBalancedPort() {
        try {
            const response = await fetch('/get-port');
            if (response.ok) {
                const text = await response.text();
                const nextPortMatch = text.match(/Using port: (\d+)/);
                if (nextPortMatch && nextPortMatch[1]) {
                    const nextPort = nextPortMatch[1];
                    if (nextPort !== currentPort) {
                        const newUrl = window.location.protocol + '//' +
                                       window.location.hostname + ':' + nextPort +
                                       window.location.pathname + window.location.search + window.location.hash;
                        window.location.replace(newUrl);
                    }
                } else {
                    console.error('Failed to parse port from response:', text);
                }
            } else {
                console.error('Failed to fetch load balanced port:', response.statusText);
            }
        } catch (error) {
            console.error('Error fetching load balanced port:', error);
        }
    }

    // redirectToLoadBalancedPort(); // Temporarily disabled for debugging
</script>
<div class="login-container">
    <div class="login-header">
        <h2>校园二手交易平台</h2>
        <p>请使用学号和密码登录</p>
    </div>
    <form id="loginForm">
        <div class="form-group">
            <label for="studentId">学号:</label>
            <input type="text" id="studentId" name="studentId" required>
        </div>
        <div class="form-group">
            <label for="password">密码:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit" class="login-btn">登录</button>
    </form>
    <div class="register-link">
        <a href="register.html">还没有账号？立即注册</a>
    </div>
</div>

<script>
    document.getElementById('loginForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const studentId = document.getElementById('studentId').value;
        const password = document.getElementById('password').value;

        try {
            const response = await fetch('/api/users/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    studentId: studentId,
                    password: password
                })
            });

            if (response.ok) {
                const authResponse = await response.json();
                localStorage.setItem('token', authResponse.token);
                localStorage.setItem('user', JSON.stringify(authResponse.user));

                if (authResponse.user.userRole === 'admin') {
                    window.location.href = 'admin.html';
                } else {
                    window.location.href = 'index.html';
                }
            } else {
                alert('登录失败，请检查学号和密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            alert('登录失败，请稍后重试');
        }
    });
</script>
</body>
<script>
    window.onload = function() {
        // 检查URL中是否已经包含了'switched'标志，防止无限循环刷新
        if (!sessionStorage.getItem('switched')) {
            const ports = ['8083', '8084'];
            const currentPort = window.location.port;
            let nextPort;

            if (currentPort === ports[0]) {
                nextPort = ports[1];
            } else {
                nextPort = ports[0];
            }

            // 设置一个标志，表示已经切换过一次
            sessionStorage.setItem('switched', 'true');

            const newUrl = window.location.protocol + '//' + window.location.hostname + ':' + nextPort + window.location.pathname;
            
            // 跳转到新的URL
            window.location.href = newUrl;
        } else {
            // 如果已经切换过，就清除标志，以便下次手动刷新时可以再次切换
            sessionStorage.removeItem('switched');
        }

        // 调用后端的/port接口，让其在控制台打印端口
        fetch('/port');
    };
</script>
</html>